package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;  //用于添加菜品

    @Autowired
    private FlavorMapper flavorMapper;  //用于添加口味
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     * @param dto
     */
    @Override
    @Transactional  //使口味表以及菜品表的操作同时成功或失败
    public void insertWithFlavor(DishDTO dto) {
        //向菜品表添加数据
        //获取菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.insert(dish);

        //获取insert语句生成的主键值，用于给口味数据添加dishId
        Long dishId = dish.getId();

        //向口味表添加数据
        List<DishFlavor> flavorList = dto.getFlavors();
        if (flavorList != null && flavorList.size() != 0){
            //给List中每条数据都添加dishId
            flavorList.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            flavorMapper.insertBatch(flavorList);   //批量添加数据
        }
    }


    /**
     * 分页查询菜品
     * @param dto
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize()); //启动分页

        Page<DishVO> page = dishMapper.list(dto);
        log.info("查询到的数据为：{}", page);

        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 删除菜品
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //判断菜品是否处于启售状态，若是则不允许删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE)
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断菜品是否位于套餐当中，若是则不允许删除
        List<SetmealDish> setmealDishes = setmealMapper.select(ids);
        if (setmealDishes != null && setmealDishes.size() > 0)
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);

        //删除菜品以及对应风味数据
        dishMapper.delete(ids);
        flavorMapper.delete(ids);
    }


    /**
     * 根据id查询菜品视图
     * @param id
     * @return
     */
    @Override
    public DishVO selectById(Long id) {
        DishVO dishVO = dishMapper.getVOById(id);

        return dishVO;
    }


    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional
    public void update(DishDTO dto) {
        //修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.update(dish);

        if (dto.getFlavors() != null && dto.getFlavors().size() > 0){
            //修改口味
            //先删除再新增
            //根据菜品id删除口味
            flavorMapper.deleteById(dto.getId());
            //新增菜品口味
            List<DishFlavor> flavorList = dto.getFlavors();
            for (DishFlavor dishFlavor : flavorList) {  //为口味设置关联的菜品id
                dishFlavor.setDishId(dto.getId());
            }
            flavorMapper.insertBatch(flavorList);   //批量插入
        }
    }


    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        return dishList;
    }


    /**
     * 更改菜品状态
     * @param status
     */
    @Override
    public void updateStatus(String status, Long id) {
        Dish dish = Dish.builder()
                .status(Integer.valueOf(status))
                .id(id)
                .build();
        dishMapper.update(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listByDish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
